﻿using RabbitMQ.Client;
using System.Collections.Concurrent;
using Volo.Abp.DependencyInjection;

namespace FlyingEye.Common
{
    public enum ProcessNames
    {
        /// <summary>
        /// 搅拌工序
        /// </summary>
        MixingProcess,

        /// <summary>
        /// 极片分类
        /// </summary>
        MaterialClassification
    }

    public static class RabbitMQVirtualHostExtensions
    {
        public static string ToStringHost(this ProcessNames processName)
        {
            return processName switch
            {
                ProcessNames.MixingProcess => "flyingeye.mixing.process",
                ProcessNames.MaterialClassification => "flyingeye.material.classification",
                _ => throw new InvalidOperationException("无效的虚拟主机。")
            };
        }
    }

    public class RabbitMQFactory : ISingletonDependency
    {
        /// <summary>
        /// 使用枚举强类型比使用字符串更安全一些。
        /// </summary>
        private readonly ConcurrentDictionary<ProcessNames, IModel> _models = new();

        private IModel CreateModel(string rabbitMQVirtualHost)
        {
            var factory = new ConnectionFactory() { HostName = "172.18.64.150", Port = 65531, DispatchConsumersAsync = true };

            factory.VirtualHost = rabbitMQVirtualHost;
            factory.UserName = "admin";
            factory.Password = "admin";

            IConnection? connection = factory.CreateConnection();

            return connection.CreateModel();
        }

        public IModel GetModel(ProcessNames virtualHost)
        {
            return _models.GetOrAdd(virtualHost, CreateModel(virtualHost.ToStringHost()));
        }
    }
}
